import ProCard from '@ant-design/pro-card';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Empty } from 'antd';
import { Typography } from 'antd';
import ReactMarkdown from 'react-markdown';

const { Text } = Typography;

const useResize = (myRef) => {
    const getWidth = useCallback(() => myRef?.current?.offsetWidth, [myRef]);

    const [width, setWidth] = useState(undefined);

    useEffect(() => {
        const handleResize = () => {
            setWidth(getWidth());
        };

        if (myRef.current) {
            setWidth(getWidth());
        }

        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, [myRef, getWidth]);

    return width && width > 25 ? width - 25 : width;
};

const MarkdownPannel = (props) => {
    const configs = props.configs;
    const data = props.data;
    console.log(data)
    const divRef = useRef(null);
    const maxWidth = useResize(divRef);
    //ReactMarkdown accepts custom renderers
    const renderers = {
        //This custom renderer changes how images are rendered
        //we use it to constrain the max width of an image to its container
        img: ({
            alt,
            src,
            title,
        }) => (
            <img
                alt={alt}
                src={src}
                title={title}
                style={{ maxWidth: maxWidth }} />
        ),
    };

    return (
        <ProCard
            title={configs.title}
            style={{ marginTop: 16, ...props.style }} 
            bordered collapsible
            tooltip={!!configs.tooltips ? configs.tooltips : ""}
        // bodyStyle={{ padding: 0 }}
        >
            {
                data ?
                    <div
                        ref={divRef}
                    >
                        <ReactMarkdown
                            // source={input}
                            components={{
                                ...renderers
                            }}
                        >
                            {data}
                        </ReactMarkdown>
                    </div>
                    : <Empty style={{ marginBottom: 20 }} image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={
                            <div>Datasource  <Text type="danger"> {configs?.datasource} </Text> no data</div>
                        } />

            }
        </ProCard>

    )
}

export default MarkdownPannel